import { defineStore } from 'pinia'
import http from '@/http'

// 为后端返回的 Token 对象定义一个清晰的类型
interface TokenResponse {
  token: string
}

export interface UserState {
  id: number | null
  username: string
  role: 'USER' | 'ADMIN' | ''
  avatarUrl?: string
  resumeUrls?: []
  intro: ''
  token?: string
  resumeArticleId: ''
  profileDrawerVisible: boolean
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    id: null,
    username: '',
    role: '',
    avatarUrl: '',
    resumeUrls: [],
    intro: '',
    token: localStorage.getItem('token') || '',
    resumeArticleId: '',
    profileDrawerVisible: false,
  }),
  actions: {
    async login(username: string, password: string) {
      // TypeScript 现在也能正确推断出 res 的类型是 TokenResponse
      const res = await http.post<TokenResponse, TokenResponse>('/api/auth/login', {
        username,
        password,
      })
      this.token = res.token
      localStorage.setItem('token', this.token)
      await this.fetchUserInfo()
    },
    async register(username: string, password: string, avatarUrl: string) {
      // 將頭像 URL 連同使用者名稱和密碼一起傳送給後端
      const res = await http.post<TokenResponse, TokenResponse>('/api/auth/register', {
        username,
        password,
        avatarUrl,
      })

      this.token = res.token
      localStorage.setItem('token', this.token)
      await this.fetchUserInfo()
    },
    async fetchUserInfo() {
      if (!this.token) return
      try {
        // http.get 的返回值直接就是 UserState 对象
        const userInfo: any = await http.get<UserState, UserState>('/api/users/me')
        this.id = userInfo.id
        this.username = userInfo.username
        this.role = userInfo.role
        this.avatarUrl = userInfo.avatarUrl
        // 1. 检查后端是否返回了 resumeUrls 字段
        if (userInfo.resumeUrls && typeof userInfo.resumeUrls === 'string') {
          // 2. 如果有，就用逗号分割成数组并存入 state
          this.resumeUrls = userInfo.resumeUrls.split(',')
        } else {
          // 3. 如果没有，就确保它是一个空数组
          this.resumeUrls = []
        }

        this.intro = userInfo.intro
        this.resumeArticleId = userInfo.resumeArticleId
      } catch (error) {
        console.error('获取用户信息失败, Token 可能已过期:', error)
        this.logout()
      }
    },
    logout() {
      this.id = null
      this.username = ''
      this.role = ''
      this.token = ''
      this.avatarUrl = ''
      localStorage.removeItem('token')
      window.location.href = '/login'
    },
    // 核心新增：打開和關閉抽屜的方法
    openProfileDrawer() {
      this.profileDrawerVisible = true
    },
    closeProfileDrawer() {
      this.profileDrawerVisible = false
    },
  },
})
